import doc.resources.CommandWord;

import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.IOException;
/**
 * This class is the main class of the "World of Zuul" application.
 * "World of Zuul" is a very simple, text based adventure game.  Users
 * can walk around some scenery. That's all. It should really be extended
 * to make it more interesting!
 * <p>
 * To play this game, create an instance of this class and call the "play"
 * method.
 * <p>
 * This main class creates and initialises all the others: it creates all
 * rooms, creates the parser and starts the game.  It also evaluates and
 * executes the commands that the parser returns.
 *
 * @author Michael Kölling and David J. Barnes
 * @version 2016.02.29
 */

public class Game {
    private Parser parser;
    private Room currentRoom;
    private Player player;
    private PackBag bag;


    /**
     * Create the game and initialise its internal map.
     */
    public Game() throws IOException, UnsupportedAudioFileException, LineUnavailableException {
        // Enter the main command loop.  Here we repeatedly read commands and
        // execute them until the game is over.
        createRooms();
        parser = new Parser();
        player = new Player();
        bag = new PackBag();
        player.setBag(bag);
        bag.addBall();
        bag.addBall();
        player.getBag().getEmptyPokeBall().addPokemon(new Pikaqiu());
    }


    /**
     * Create all the rooms and link their exits together.
     */
    private void createRooms() {
        Room zhenxin, kuye, nibi, caihong, hualan, dishudong,honglian,yuejianshan;

        // create the rooms
        zhenxin = new Room("你在出生地 真新镇");
        kuye = new Room("你在真新镇的北方 枯叶市");
        kuye.addPokemon(new jienigui());
        kuye.setPokeballs("pokeball",1);
        nibi = new Room("你在真新镇的南方 尼比市");
        nibi.addPokemon(new Lvmaochong());
        nibi.setPokeballs("pokeball",1);
        caihong = new Room("你在真新镇的西方 彩虹市");
        caihong.setPokeballs("pokeball",3);
        hualan = new Room("你在彩虹市的西方 华蓝市");
        hualan.addPokemon(new Miaowa());
        dishudong = new Room("你在华蓝市的下方 地鼠洞");
        dishudong.setPokeballs("pokeball",2);
        dishudong.addPokemon(new Sandishu());
        honglian = new Room("你在尼比市的南方 红莲岛");
        honglian.addPokemon(new Xiaohuolong());
        yuejianshan = new Room("你在红莲岛的上方 月见山");
        yuejianshan.addPokemon(new Chaomeng());
        // initialise room exits
//        outside.setExits(null, theater, lab, pub);
//        theater.setExits(null, null, null, outside);
//        pub.setExits(null, outside, null, null);
//        lab.setExits(outside, office, null, null);
//        office.setExits(null, null, null, lab);
        zhenxin.setExit("north", kuye);
        kuye.setExit("south",zhenxin);
        zhenxin.setExit("south", nibi);
        zhenxin.setExit("west", caihong);
        caihong.setExit("west", hualan);
        caihong.setExit("east", zhenxin);
        hualan.setExit("east", caihong);
        hualan.setExit("down", dishudong);
        dishudong.setExit("up",hualan);
        nibi.setExit("north",zhenxin);
        nibi.setExit("south",honglian);
        honglian.setExit("north",nibi);
        honglian.setExit("up",yuejianshan);
        yuejianshan.setExit("down",honglian);
        currentRoom = zhenxin;  // start game outside
    }

    /**
     * Main play routine.  Loops until end of play.
     */
    public void play() throws InterruptedException {
        MyThread mythread1=new MyThread("ManyThread");
        mythread1.start();

        printWelcome();
        // Enter the main command loop.  Here we repeatedly read commands and
        // execute them until the game is over.

        boolean finished = false;
        while (!finished) {
            Command command = parser.getCommand();
            finished = processCommand(command);
        }
        System.out.println("Thank you for playing.  Good bye.");
        mythread1.interrupt();
    }

    /**
     * Print out the opening message for the player.
     */
    private void printWelcome() throws InterruptedException {
        System.out.println();
        System.out.println("欢迎来到《精灵宝可梦前传》!");
        MyThread.sleep(400);
        System.out.println("你的名字叫小聪明蛋儿智，你昏迷醒来，迷失在宝可梦大陆");
        MyThread.sleep(700);
        System.out.println("现在你有一只宝可梦皮卡丘，和两个多余的精灵球");
        MyThread.sleep(600);
        System.out.println("你需要找到并打败boss才能开启回家的通道！！！");
        MyThread.sleep(700);
        System.out.println("提示：输入 go空格出口 进行移动，例如go east.输入help查看帮助");
        currentRoom.getDescription();
        if (currentRoom.checkPokeball()){
            int num=currentRoom.getPokeballs();
            while (num>0) {
                player.getBag().addBall();
                num--;
            }
        }
        currentRoom.printExits();
    }

    /**
     * Given a command, process (that is: execute) the command.
     *
     * @param command The command to be processed.
     * @return true If the command ends the game, false otherwise.
     */
    private boolean processCommand(Command command) throws InterruptedException {
        boolean wantToQuit = false;

        if (command.isUnknown()) {
            System.out.println("I don't know what you mean...");
            return false;
        }
        String commandWord = command.getCommandWord();
        CommandWord cmd = CommandWord.valueOf(commandWord.toUpperCase());
        switch (cmd) {
            case GO:
                goRoom(command);
                break;
            case CATCH:
                catchPokemon(command);
                break;
            case HELP:
                printHelp();
                break;
            case QUIT:
                wantToQuit = quit(command);
                break;
            case FIGHT:
                wantToQuit = fight(command);
        }
//        if (commandWord.equals("help")) {
//            printHelp();
//        }
//        else if (commandWord.equals("go")) {
//            player.walk();
//            player.isAlive();
//            goRoom(command);
//        }
//        else if (commandWord.equals("quit")) {
//            wantToQuit = quit(command);
//        }
//        else if (commandWord.equals("eat")){
//            eat(command);
//        }


        return wantToQuit;
    }

    // implementations of user commands:

    /**
     * Print out some help information.
     * Here we print some stupid, cryptic message and a list of the
     * command words.
     */
    private void printHelp() {
        System.out.println("你失忆了，你的潜意识告诉你要寻找到神秘宝可梦");
        System.out.println("快去捕捉更多宝可梦，击败BOSS吧！");
        System.out.println("ps:捕捉失败消耗一个精灵球,每移动一次自动将战败宝可梦HP恢复至100");
        System.out.println("在一个地区你的所有宝可梦都战败则游戏失败");
        CommandWords.printCommands();
    }


    private void catchPokemon(Command command) {
        if (player.getBag().getEmptyPokeBall()==null) {
            // if there is no second word, we don't know where to go...
            System.out.println("没有多余精灵球");
            return;
        }
        if (currentRoom.getPokemon().isHealth()) {
            System.out.println("请先击败当前房间的宝可梦");
            return;
        }
        String wantPokemon = command.getSecondWord();
        if (!player.getBag().getEmptyPokeBall().catchPokemon(currentRoom.getPokemon())) {
            player.getBag().dropPokeball();
        }
        //player.eat(currentRoom.getPokemon(wantFood));

    }

    private void restoreHealth(){
        player.getBag().restoreHealth();
    }

    /**
     * Try to go in one direction. If there is an exit, enter
     * the new room, otherwise print an error message.
     */
    private void goRoom(Command command) throws InterruptedException {
        if (!command.hasSecondWord()) {
            // if there is no second word, we don't know where to go...
            System.out.println("去哪?");
            return;
        }
        String direction = command.getSecondWord();
        Room nextRoom = currentRoom.goNext(direction);
//        // Try to leave current room.
//        Room nextRoom = null;
//        if(direction.equals("north")) {
//            nextRoom = currentRoom.northExit;
//        }
//        if(direction.equals("east")) {
//            nextRoom = currentRoom.eastExit;
//        }
//        if(direction.equals("south")) {
//            nextRoom = currentRoom.southExit;
//        }
//        if(direction.equals("west")) {
//            nextRoom = currentRoom.westExit;
//        }
        if (nextRoom == null) {
            System.out.println("没有出口!");
        } else {
            currentRoom = nextRoom;
            restoreHealth();
            if (currentRoom.checkPokeball()) {
                int num=currentRoom.getPokeballs();
                while (num>0) {
                    player.getBag().addBall();
                    num--;
                }
                currentRoom.dropPokeballs();
            }
            MyThread.sleep(400);
            currentRoom.getDescription();
            MyThread.sleep(800);
            currentRoom.printExits();
            MyThread.sleep(700);
            if (currentRoom.checkPokemon()!="") {
                if (currentRoom.getPokemon().isOnRoom()){
                    System.out.println("宝可梦对决开始！你拥有的宝可梦：");
                    System.out.println(player.getBag().checkPokeBall());
                    System.out.println("输入fight (出战宝可梦名字) 来发起战斗");
                    System.out.println("例如 ‘fight 皮卡丘’");
                }
//                if (player.getBag().checkPokemon()){
//                    fight(commandWord);
//                }else System.out.println("你没有该神奇宝贝");
            }
        }
    }

    private boolean fight(Command command) throws InterruptedException {
        System.out.println("--------------------");
        String direction = command.getSecondWord();
        Pokemon pp = player.getBag().getPokemon(direction);
        Pokemon enemy = currentRoom.getPokemon();
        if (pp!=null){
            while (pp.isHealth() & enemy.isHealth()){
                MyThread.sleep(1000);
                pp.attack(enemy);
                if (pp.isHealth() & enemy.isHealth()){
                    MyThread.sleep(1000);
                    enemy.attack(pp);
                }
                if (!enemy.isHealth()){
                    if (enemy.getName()!="超梦") {
                        System.out.println("可以输入catch尝试捕捉房间中的宝可梦");
                    }else {
                        MyThread.sleep(600);
                        System.out.println("...");
                        MyThread.sleep(700);
                        System.out.println("恭喜你 战胜 了 超梦！！！");
                        MyThread.sleep(600);
                        System.out.println("忽然脑袋一阵眩晕，你...");
                        MyThread.sleep(600);
                        System.out.println("睁开了眼睛...");
                        MyThread.sleep(700);
                        System.out.println("原来一切都是一个梦...");
                        MyThread.sleep(600);
                        System.out.println("你今天应该去找博士领取第一只宝可梦开启真正的宝可梦之旅");
                        MyThread.sleep(1000);
                        System.out.println("!!!----------恭喜通关《精灵宝可梦：前瞎鸡儿扯传》-----------!!!");
                        return true;
                    }
                }
                if (!pp.isHealth()) {
                    if (!player.getBag().checkAlivePokemon()) {
                        System.out.println("你所有宝可梦都已经战败，游戏结束");
                        return true;
                    }else {
                        System.out.println("当前出战宝可梦战败，可尝试使用其他宝可梦");
                        return false;
                    }
                }
            }
            System.out.println("--------------------");
            return false;
        }else {
            System.out.println("你没有该宝可梦");
            return false;
        }

    }
    /**
     * "Quit" was entered. Check the rest of the command to see
     * whether we really quit the game.
     *
     * @return true, if this command quits the game, false otherwise.
     */
    private boolean quit(Command command) {
        if (command.hasSecondWord()) {
            System.out.println("Quit 啥?");
            return false;
        } else {
            return true;  // signal that we want to quit
        }
    }
}
